#include <string.h>
#include <iostream>

using std::cout;
using std::endl;


class String
{    
public:
    //String str1;
    String()
    /* : _pstr(nullptr) */
    : _pstr(new char[1]())
    {
        cout << "String()" << endl;
    }

    String(const char * pstr)
    : _pstr(new char[strlen(pstr) + 1]())
    {
        cout << "String(const char *)" << endl;
        strcpy(_pstr, pstr);
    }

    String(const String & rhs)
    : _pstr(new char[strlen(rhs._pstr) + 1]())
    {
        cout << "String(const String &)" << endl;
        strcpy(_pstr, rhs._pstr);
    }

    //str1 = str2;
    String & operator=(const String & rhs)
    {
        cout << "String &operator=(const String &)" << endl;
        if(this != &rhs)
        {
            if(_pstr)
            {
                delete [] _pstr;
            }
            _pstr = new char[strlen(rhs._pstr) + 1]();
            strcpy(_pstr, rhs._pstr);
        }
        return *this;
    }

    size_t length() const
    {
        size_t len = 0;
        if(_pstr)
        {
            len = strlen(_pstr);
        }

        return len;

    }

    const char * c_str() const
    {
        if(_pstr)
        {
            return _pstr;
        }
        else
        {
            return nullptr;
        }
    }


    ~String()
    {
        cout << "~String()" << endl;
        if(_pstr)
        {
            delete [] _pstr;
            _pstr = nullptr;
        }
    }

    void print() const
    {
        if(_pstr){
            cout << "_pstr = " << _pstr << endl;
        }else{
            cout << endl;
        }
    }

private:
    char * _pstr;
};

int main(void)
{
    /* String str1; */
    /* str1.print(); */

    cout << endl;
    //隐式转换
    //C++11标准下
    //编译器会利用const char *作为构造函数的参数
    //初始化一个临时的（匿名的）String对象
    //然后再调用拷贝构造初始化str2
    String str2 = "Hello,world";
    String str3("wangdao");
    /* str2.print(); */		
    /* str3.print(); */	

    /* cout << endl; */
    /* String str4 = str3; */
    /* str4.print(); */

    /* cout << endl; */
    /* str4 = str2; */
    /* str4.print(); */

    /* const char * pstr = str3.c_str(); */
    /* cout << pstr << endl; */

    return 0;
}



